#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# QQ: 34538980@qq.com
# Jekkay Hu, 2013.5.5
# ///////////////////////////////////////////////////////////////////
#                            _ooOoo_                               //
#                           o8888888o                              //
#                           88" . "88                              //
#                           (| ^_^ |)                              //
#                           O\  =  /O                              //
#                        ____/`---'\____                           //
#                      .'  \\|     |//  `.                         //
#                     /  \\|||  :  |||//  \                        //
#                    /  _||||| -:- |||||-  \                       //
#                    |   | \\\  -  /// |   |                       //
#                    | \_|  ''\---/''  |   |                       //
#                    \  .-\__  `-`  ___/-. /                       //
#                  ___`. .'  /--.--\  `. . ___                     //
#                ."" '<  `.___\_<|>_/___.'  >'"".                  //
#              | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //
#              \  \ `-.   \_ __\ /__ _/   .-` /  /                 //
#        ========`-.____`-.___\_____/___.-`____.-'========         //
#                             `=---='                              //
#        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
#             佛祖保佑       永无BUG        运行正常                   //
#     -------------------------------------------------------      //
#               QQ: 34538980@qq.com                                //
#               博客: http://www.easysb.cn                          //
#               Jekkay Hu, 2013.5.5                                //
# ///////////////////////////////////////////////////////////////////
#
#  将工作线程池的扫描结果同步到数据库中
#
import logging
import time
from scan.base_db_op_thread import BaseDBOpThread

SQL_QUERY_TARGET = 'SELECT * FROM target where `domain_id`=%(domain_id)s AND `target`=%(target)s'
SQL_INSERT_TARGET = ('INSERT INTO target(`id`, `domain_id`, `domain`, `title`,`target`, `match`, `create_time`) VALUES'
                     '(%(id)s, %(domain_id)s, %(domain)s, %(title)s, %(target)s, %(match)s, %(create_time)s)')


class TargetSyncThread(BaseDBOpThread):
    def __init__(self, result_target_queue):
        super(TargetSyncThread, self).__init__()
        self.result_target_queue = result_target_queue

    def work_loop(self):
        self.is_working = False
        if self.result_target_queue.qsize() <= 0:
            time.sleep(0.1)
            return
        target = self.result_target_queue.get()
        self.is_working = True
        if target and not self._save_target(target):
            time.sleep(1)

    def _save_target(self, target):
        try:
            # query
            res = self.db.query(SQL_QUERY_TARGET, {
                'domain_id': target.domain_id,
                'target': target.target
            })
            # 已经存在就不需要插入
            if res:
                return True
            # 插入数据
            self.db.execute(SQL_INSERT_TARGET, target.__dict__)
            logging.info(" >> save to dabase [ %s ] [ %s ]" % (target.domain, target.title))
            return True
        except Exception as e:
            logging.error('_save_target exception %s' % str(e))
